#include "teachdialog.h"
#include "qevent.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QPushButton>
// 添加 QHeaderView 头文件
#include <QHeaderView>
#include <QScrollBar>
#include <QDebug>
#include <QScroller>
#include <models/robotlist.h>
#include <models/command.h>
#include <models/syssettingmodel.h>
TeachDialog::TeachDialog(DialogType type, TeachModel* model,int nIndex,QWidget *parent)
    :PopupDialog(parent),
    curType(type),
    pCurmodel(model)
{
    // 隐藏自带标题栏
    // 设置背景颜色
    //setStyleSheet("QWidget{background-color:#55585E;}");
    //setWindowFlags(Qt::FramelessWindowHint);
    setFixedSize(900*g_xScale,650*g_xScale);
    QString btnStyle =QString("QPushButton{"
                               "background:transparent;"
                               "color:#007BFF;"
                               "font:%1px \"微软雅黑\";"
                               "border-color: #098CFF;"
                               "border-width:1px;}"
                               "QPushButton:pressed{"
                               "color:#0056b3;}").arg(int(20*g_xScale));
    QString labelStyle =QString("QLabel{"
                                 "background:transparent;"
                                 "color:white;"
                                 "font:%1px \"微软雅黑\";}").arg(int(18*g_xScale));
    QString editStyle = QString("QLineEdit{"
                                "background-color: #232426;" /* 背景颜色 */
                                "color:white;"
                                "font:%1px \"微软雅黑\";"
                                "border:1px  solid  #48494E"
                                "padding-left: 5px"
                                "}"
                                "QLineEdit:focus {"
                                "border: 1px solid #098CFF;"
                                "}").arg(int(18*g_xScale));
    QHBoxLayout *titleLayout = new QHBoxLayout();
    QString title;
    if(curType==ADD_DIALOG)
        title="添加示教";
    else
        title="编辑示教";
    titleLabel = new QLabel(title,this);
    titleLabel->setStyleSheet(QString("QLabel{"
                                      "background:transparent;"
                                      "color:white;"
                                      "font:%1px \"微软雅黑\";}").arg(int(20*g_xScale)));
    closeButton = new TouchButton(this);
    closeButton->setFixedSize(40*g_xScale, 40*g_xScale);
    closeButton->setStyleSheet("QPushButton{"
                               "   background-image: url(:/images/close.png);"
                               "   background-color:transparent;"
                               "   background-repeat:no-repeat;"
                               "   background-position:center;"
                               "    border-radius: 0px;}"
                               "QPushButton:pressed{"
                               "background-color: rgb(255, 0, 0);"
                               "}");
    connect(closeButton, &QPushButton::clicked, this, &TeachDialog::closeDialog);
    titleLayout->addWidget(titleLabel);
    titleLayout->addStretch();
    titleLayout->addWidget(closeButton);

    // 创建主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(30*g_xScale,20*g_xScale,30*g_xScale,20*g_xScale);
    mainLayout->setSpacing(15*g_xScale);
    //mainLayout->addStretch();
    mainLayout->addLayout(titleLayout);


    // 示教名称输入框和添加点按钮
    QHBoxLayout *nameAndButtonLayout = new QHBoxLayout();
    QLabel *nameLabel = new QLabel("示教名称:");
    nameLabel->setStyleSheet(labelStyle);
    nameEdit = new QLineEdit;
    nameEdit->setStyleSheet(editStyle);
    nameEdit->setFixedSize(300*g_xScale,50*g_yScale);
    nameEdit->setValidator(new QRegExpValidator(QRegExp("[\u4e00-\u9fa5a-zA-Z0-9]+"), this));


    addPointButton = new TouchButton("添加点");
    addPointButton->setStyleSheet(btnStyle);
    addPointButton->setFixedWidth(100*g_xScale);
    connect(addPointButton, &QPushButton::clicked, this, &TeachDialog::onAddBtn);
    nameAndButtonLayout->addWidget(nameLabel);
    nameAndButtonLayout->addWidget(nameEdit);
    nameAndButtonLayout->addStretch();
    nameAndButtonLayout->addWidget(addPointButton);
    mainLayout->addLayout(nameAndButtonLayout);
    QString tableStyle = QString(
                             "QTableWidget {"
                             "    background-color: transparent;"
                             "    border: 1px solid #3E3E40;"
                             "    color: white;"
                             "    gridline-color: #3E3E40;"
                             "    font:%1px \"微软雅黑\";"
                             "    border-top: none;"
                             "}"
                             "QHeaderView::section {"
                             "    background-color: #3E3E40;"
                             "    color: white;"
                             "    padding: 5px;"
                             "    border: 1px  #3E3E40;"
                             "    font-family: '微软雅黑';"
                             "    border-image: none;"
                             "}"
                             "QTableWidget::item {"
                             "    color: white;"
                             "    background-color: transparent;"
                             "    border-image: none;"
                             "    height: 25px;"
                             "    font:%1 \"微软雅黑\";"
                             "}"
                             "QHeaderView {"
                             "    background-color: #3E3E40;"
                             "    font:%1 \"微软雅黑\";"
                             "    border-image: none;"
                             "    height: %2px;"
                             "}"
                             "QHeaderView::section {"
                             "    height: %1px;"
                             "    background-color: #232426;"
                             "    color: white;"
                             "    font: %1px '微软雅黑';"
                             "    border: none;"
                             "    border-bottom: 1px solid #48494E;"
                             "    border-right: 1px solid #48494E;"
                             "    padding-left: 5px;"
                             "}"
                             "QScrollBar:vertical {"
                             "    background-color: #2E2F31;"
                             "    width: 10px;"
                             "    margin: 0px;"
                             "    padding-top:50;"
                             "}"
                             "QScrollBar::handle:vertical {"
                             "    background-color: #3E3E40;"
                             "    min-height: 20px;"
                             "}"
                             "QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {"
                             "    height: 0px;"
                             "}").arg(int(20*g_yScale)).arg(int(40*g_yScale));

    // 列表
    tableWidget = new QTableWidget(0, 4);
    QScroller::grabGesture(tableWidget, QScroller::LeftMouseButtonGesture);

    tableWidget->setFixedSize(width()-60*g_xScale,370*g_xScale);
    tableWidget->horizontalScrollBar()->hide();
    tableWidget->setStyleSheet(tableStyle);
    // 隐藏列表序号
    tableWidget->verticalHeader()->setVisible(false);
    // 禁用水平表头的点击功能
    tableWidget->horizontalHeader()->setSectionsClickable(false);   // 禁用表头点
    tableWidget->horizontalHeader()->setFixedHeight(50*g_xScale);           // 固定表头高度;
    QStringList headers;
    headers << "编号" << "执行时间" << "等待时间" << "操作";
    tableWidget->setHorizontalHeaderLabels(headers);
    // 设置列占满整个宽度
    tableWidget->horizontalHeader()->setSectionResizeMode(3,QHeaderView::Stretch);
    // 设置编号和操作列宽度
    tableWidget->setColumnWidth(0, 100*g_xScale); // 编号列
    tableWidget->setColumnWidth(1, (tableWidget->width()-260*g_xScale)/2);
    tableWidget->setColumnWidth(2, (tableWidget->width()-260*g_xScale)/2);
    tableWidget->setColumnWidth(3, 160*g_xScale); // 操作列
    // 设置表内容高度
    tableWidget->verticalHeader()->setDefaultSectionSize(40*g_xScale);

    // ********************解决点击滑动显示bug***********start
    QWidget *line=new QWidget();
    line->setFixedSize(tableWidget->width(),1);
    line->setStyleSheet("QWidget {"
                        "    background-color: #3E3E40;"
                        "}");
    QVBoxLayout *tempLayout = new QVBoxLayout();
    tempLayout->setContentsMargins(0,0,0,0);
    tempLayout->setSpacing(0);
    tempLayout->addWidget(line);
    tempLayout->addWidget(tableWidget);
    mainLayout->addLayout(tempLayout);
    // ********************解决点击滑动显示bug***********end
    QString style= QString("QPushButton {"
                            "    background-color: #007BFF;"
                            "    color: white;"
                            "    border-radius: %1px;"
                            "    padding: 0px;"
                            "    font: %2px \"微软雅黑\";"
                            "    margin: 0px 10px 0px 0px;"
                            "}"
                            "QPushButton:pressed {"
                            "    background-color: #0056b3;"
                            "}").arg(int(5*g_xScale)).arg(int(20*g_xScale));
    // 确定和取消按钮
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    buttonLayout->setContentsMargins(0,0,0,0);
    okButton = new TouchButton("确定");
    okButton->setFixedSize(120*g_xScale,50*g_yScale);
    okButton->setStyleSheet(style);
    cancelButton = new TouchButton("取消");
    cancelButton->setFixedSize(120*g_xScale,50*g_yScale);
    cancelButton->setStyleSheet(style);
    connect(okButton, &QPushButton::clicked, this, &TeachDialog::onOK); //
    connect(cancelButton, &QPushButton::clicked, this, &QDialog::reject);

    QHBoxLayout *errorLayout = new QHBoxLayout();
    errorLabel=new QLabel();
    errorLabel->setContentsMargins(0,0,0,0);
    errorLabel->setFixedHeight(20*g_xScale);

    errorLabel->setStyleSheet(QString("QLabel{"
                                      "background:transparent;"
                                      "color:red;"
                                      "font:%1px \"微软雅黑\";}").arg(int(14*g_xScale)));
    errorLayout->addStretch();
    errorLayout->addWidget(errorLabel);
    errorLayout->addStretch();

    // 按钮居中显示
    buttonLayout->addStretch();
    buttonLayout->addWidget(okButton);
    buttonLayout->addWidget(cancelButton);
    buttonLayout->addStretch();
    mainLayout->addLayout(errorLayout);
    mainLayout->addLayout(buttonLayout);
    mainLayout->addStretch();

    if(curType==EDIT_DIALOG)
    {
        vTeachData = pCurmodel->getTeachData(nIndex);
        for (auto teach:vTeachData)
            addPoint(teach.execTime,teach.waitTime);
    }
}

void TeachDialog::saveJoint(int nID)
{
    Robot* pCurRobot=RobotList::getInstance()->getCurRobot();
    TeachData teach;
    teach.nID=nID;
    if(pCurRobot)
    {
        teach.jointData.append(pCurRobot->getJointsArc(LEFT_ARM_JOINT));
        teach.jointData.append(pCurRobot->getJointsArc(RIGHT_ARM_JOINT));
        teach.jointData.append(pCurRobot->leftFingerArc());
        teach.jointData.append(pCurRobot->rightFingerArc());
        teach.jointData.append(pCurRobot->getJointsArc(WAIST_JOINT));
        teach.jointData.append(pCurRobot->getJointsArc(HEAD_JOINT));
    }
    teach.execTime=1000;
    teach.waitTime=1000;
    vTeachData.push_back(teach);
}

void TeachDialog::setName(QString strName)
{
    nameEdit->setText(strName);
    strOldName=strName;
}

void TeachDialog::addPoint(int execTime, int waitTime) {

    int row = tableWidget->rowCount();
    tableWidget->insertRow(row);
    if(row==vTeachData.size())
        saveJoint(row); //保存当前上肢所有关节点
    // 编号
    QTableWidgetItem *idItem = new QTableWidgetItem(QString::number(row + 1));
    // 禁用编号的编辑功能
    idItem->setFlags(idItem->flags() & ~Qt::ItemIsEditable);
    idItem->setTextAlignment(Qt::AlignCenter);
    tableWidget->setItem(row, 0, idItem);


    QString lineEditStyle=QString("QLineEdit{"
                                    "background:transparent;"
                                    "color:white;"
                                    "font:%1px \"微软雅黑\";"
                                    "border-color: #098CFF;"
                                    "border-width:1px;}"
                                    "QLineEdit:focus {"
                                    "    border: 1px solid #098CFF;"
                                    "}").arg(int(16*g_xScale));
    // 执行时间
    QLineEdit *execTimeItem = new QLineEdit(QString::number(execTime),tableWidget);
    QIntValidator *execValidator = new QIntValidator(0, 9999999, execTimeItem);
    execTimeItem->setValidator(execValidator);
    execTimeItem->setStyleSheet(lineEditStyle);
    execTimeItem->setAlignment(Qt::AlignCenter);
    tableWidget->setCellWidget(row, 1, execTimeItem);
    connect(execTimeItem, &QLineEdit::textChanged,[this,execTimeItem](){
        for (int i = 0; i < tableWidget->rowCount(); ++i) {
            QLineEdit *item=(QLineEdit*)tableWidget->cellWidget(i, 1);
            if(execTimeItem==item)
            {
                vTeachData[i].execTime= item->text().toInt();
                break;
            }
        }
    });
    // 等待时间
    QLineEdit *waitTimeItem = new QLineEdit(QString::number(waitTime),tableWidget);
    QIntValidator *waitValidator = new QIntValidator(0, 9999999, waitTimeItem);
    waitTimeItem->setValidator(waitValidator);
    waitTimeItem->setStyleSheet(lineEditStyle);
    waitTimeItem->setAlignment(Qt::AlignCenter);
    tableWidget->setCellWidget(row, 2, waitTimeItem);
    connect(waitTimeItem, &QLineEdit::textChanged,[this,waitTimeItem](){
        for (int i = 0; i < tableWidget->rowCount(); ++i) {
            QLineEdit *item=(QLineEdit*)tableWidget->cellWidget(i, 2);
            if(waitTimeItem==item)
            {
                vTeachData[i].waitTime= item->text().toInt();
                break;
            }
        }
    });


    // 创建操作按钮容器
    QWidget* buttonWidget = new QWidget(tableWidget);
    buttonWidget->setStyleSheet("background-color:#00000000");
    QHBoxLayout* buttonLayout = new QHBoxLayout(buttonWidget);
    buttonLayout->setMargin(0);

    // 删除按钮
    TouchButton *deleteButton = new TouchButton("删除",buttonWidget);
    deleteButton->setFixedSize(60*g_xScale,40*g_xScale);
        QString btnStyle=QString("QPushButton{\
                            background:transparent; \
                            color:#007BFF;\
                            font:%1px \"微软雅黑\"; \
                            border-color: #098CFF;\
                            border-width:1px;}\
                            QPushButton:pressed{ \
                            color:#0056b3; \
                            } \
                            QPushButton:disabled { \
                            color: gray; \
                            }").arg(int(18*g_xScale));
    deleteButton->setStyleSheet(btnStyle);

    // 添加按钮到布局
    buttonLayout->addStretch();
    buttonLayout->addWidget(deleteButton);
    buttonLayout->addStretch();
    // 连接删除按钮信号

    connect(deleteButton, &QPushButton::clicked, [this, idItem]() {
        // 更新编号
        for (int i = 0; i < tableWidget->rowCount(); ++i) {

            QTableWidgetItem *item=tableWidget->item(i, 0);
            if(idItem==item)
            {
                tableWidget->removeRow(i);
                vTeachData.removeAt(i);
                i--;
                continue;
            }
            item->setText(QString::number(i + 1));
        }
    });
    tableWidget->setCellWidget(row, 3, buttonWidget);
}

void TeachDialog::onAddBtn()
{
    addPoint();
}

void TeachDialog::closeDialog()
{
    reject();
}

void TeachDialog::onOK()
{
    if(nameEdit->text().isEmpty())
    {
        errorLabel->setText("示教名称不能为空！");
        return;
    }
    //处理数据后关闭窗口
    //获取数据保存到数据库并刷新列表
    QString strErr;
    if(curType==ADD_DIALOG)
    {
        if(pCurmodel->insertTeach(nameEdit->text(),vTeachData,strErr))
            QDialog::accept();
        else
            errorLabel->setText(strErr);
    }
    else{
        if(pCurmodel->editTeach(curType,nameEdit->text(),strOldName,vTeachData,strErr))
            QDialog::accept();
        else
            errorLabel->setText(strErr);
    }
}

void TeachDialog::showEvent(QShowEvent *event)
{
    Q_UNUSED(event);
    Robot *pCurRobot=RobotList::getInstance()->getCurRobot();
    if(pCurRobot)
    {
        Command cmd;
        if(SysSettingModel::getInstance()->getCmdByName("damp",cmd) != CMD_TYPE_NONE)
            pCurRobot->setUpperCmd(cmd);
    }
}


void TeachDialog::hideEvent(QHideEvent *event)
{
    Q_UNUSED(event);
    Robot *pCurRobot=RobotList::getInstance()->getCurRobot();
    if(pCurRobot)
    {
        pCurRobot->setEnable(true);
    }
}
